package com.igeek.dao;

import com.igeek.domain.User;
import com.igeek.utils.DataSourceUtils;
import com.igeek.utils.MD5Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import sun.security.provider.MD5;

import java.sql.SQLException;

public class UserDao {
    /**
     * 插入数据
     * @param user
     * @return
     */
    public int insert(User user) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="insert into user values (?,?,?,?,?,?,?,?,?,?,?)";
        String md5Pwd= MD5Utils.md5(user.getPassword());
        Object [] params={user.getUid(),user.getUsername(),md5Pwd,user.getName(),user.getEmail(),user.getAddress(),
                          user.getTelephone(),user.getBirthday(),user.getSex(),user.getState(),user.getCode()};
        return  qr.update(sql,params);
    }

    public void active(String activeCode) throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "update user set state = 1 where code = ? ";
        runner.update(sql,activeCode);
    }

    public User getUserByName(String name) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from user where username=?";
        Object [] params={name};
        return qr.query(sql,new BeanHandler<>(User.class),params);
    }

    public User login(User user) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from user where username=? and password=?";
        Object [] params={user.getUsername(),user.getPassword()};
        return qr.query(sql,new BeanHandler<>(User.class),params);
    }
}
